package main

import (
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/clients/naming_client"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
)

var client naming_client.INamingClient

/**
 * 初始化Nacos客户端
 */
func intiNacosClient() {

	sc := []constant.ServerConfig{
		{
			IpAddr: "localhost", // Nacos的服务地址
			Port:   8848,        // Nacos的服务端口
		},
	}
	//或 一种更优雅的方式来创建 ServerConfig
	_ = []constant.ServerConfig{
		*constant.NewServerConfig("console.nacos.io", 80),
	}

	cc := constant.ClientConfig{
		NamespaceId:         "",                                   // ACM的命名空间Id 当namespace是public时，此处填空字符串。
		TimeoutMs:           5000,                                 // 请求Nacos服务端的超时时间，默认是10000ms
		NotLoadCacheAtStart: true,                                 // 在启动的时候不读取缓存在CacheDir的service信息
		LogDir:              "/Users/xiaodao/Desktop/nacos/log",   // 日志存储路径
		CacheDir:            "/Users/xiaodao/Desktop/nacos/cache", // 缓存service信息的目录，默认是当前运行目录
		RotateTime:          "1h",                                 // 日志轮转周期，比如：30m, 1h, 24h, 默认是24h
		MaxAge:              3,                                    // 日志最大文件数，默认3
		LogLevel:            "debug",                              // 日志默认级别，值必须是：debug,info,warn,error，默认值是info
	}
	//或 一种更优雅的方式来创建 ClientConfig
	_ = *constant.NewClientConfig(
		constant.WithNamespaceId("e525eafa-f7d7-4029-83d9-008937f9d468"),
		constant.WithTimeoutMs(5000),
		constant.WithNotLoadCacheAtStart(true),
		constant.WithLogDir("/tmp/nacos/log"),
		constant.WithCacheDir("/tmp/nacos/cache"),
		constant.WithRotateTime("1h"),
		constant.WithMaxAge(3),
		constant.WithLogLevel("debug"),
	)

	// 一种更优雅的方式来创建命名客户端
	clientTemp, err := clients.NewNamingClient(
		vo.NacosClientParam{
			ClientConfig:  &cc,
			ServerConfigs: sc,
		},
	)

	if err != nil {
		panic(err)
	}

	client = clientTemp

}

/**
 * 输入指令
 */
func enterInstruction() int {
	var x int
	fmt.Println("1:注册  2:注销  3:查询")
	fmt.Println("请输入指令")
	fmt.Scan(&x)
	return x
}

/**
 * 流程判断
 */
func process(instruction int) {

	switch {
		//注册
		case instruction == 1:
			t1()
		//注销
		case instruction == 2:
			t2()
		//查询
		case instruction == 3:
			t3()
		case instruction == 4:
			t4()
		case instruction == 5:
			t5()
		case instruction == 6:
			t6()
		case instruction == 7:
			t7()
		case instruction == 8:
			t8()
		case instruction == 9:
			t9()
		case instruction == 10:
			t10()
		case instruction == 11:
			t11()
		case instruction == 12:
			t12()
		case instruction == 13:
			t13()
		case instruction == 14:
			t14()
		case instruction == 15:
			t15()
	}

}

func main() {

	//初始化Nacos客户端
	intiNacosClient()

	// 替代 while (true) {}
	for {
		instruction := enterInstruction()
		fmt.Printf("当前指令==>:%d\n", instruction)
		if instruction == 0 {
			return
		}
		process(instruction)
	}

}

/**
 * 注册默认集群和组
 * ClusterName=DEFAULT,GroupName=DEFAULT_GROUP
 */
func t1() {
	ExampleServiceClient_RegisterServiceInstance(client, vo.RegisterInstanceParam{
		Ip:          "10.0.0.11",
		Port:        8848,
		ServiceName: "demo.go",
		Weight:      10,
		Enable:      true,
		Healthy:     true,
		Ephemeral:   true,
		Metadata:    map[string]string{"idc": "shanghai"},
	})
}

/**
 * 使用集群名称注册
 * GroupName=DEFAULT_GROUP
 */
func t2() {
	ExampleServiceClient_RegisterServiceInstance(client, vo.RegisterInstanceParam{
		Ip:          "10.0.0.11",
		Port:        8848,
		ServiceName: "demo.go",
		Weight:      10,
		ClusterName: "cluster-a",
		Enable:      true,
		Healthy:     true,
		Ephemeral:   true,
	})
}

/**
 * 注册不同的集群
 * GroupName=DEFAULT_GROUP
 */
func t3() {
	ExampleServiceClient_RegisterServiceInstance(client, vo.RegisterInstanceParam{
		Ip:          "10.0.0.12",
		Port:        8848,
		ServiceName: "demo.go",
		Weight:      10,
		ClusterName: "cluster-b",
		Enable:      true,
		Healthy:     true,
		Ephemeral:   true,
	})
}

/**
 * 注册不同的组
 */
func t4() {
	ExampleServiceClient_RegisterServiceInstance(client, vo.RegisterInstanceParam{
		Ip:          "10.0.0.13",
		Port:        8848,
		ServiceName: "demo.go",
		Weight:      10,
		ClusterName: "cluster-b",
		GroupName:   "group-a",
		Enable:      true,
		Healthy:     true,
		Ephemeral:   true,
	})

	ExampleServiceClient_RegisterServiceInstance(client, vo.RegisterInstanceParam{
		Ip:          "10.0.0.14",
		Port:        8848,
		ServiceName: "demo.go",
		Weight:      10,
		ClusterName: "cluster-b",
		GroupName:   "group-b",
		Enable:      true,
		Healthy:     true,
		Ephemeral:   true,
	})
}

/**
 * 使用 ip,port,serviceName 注销  ClusterName=DEFAULT, GroupName=DEFAULT_GROUP
 * Note:ip=10.0.0.10,port=8848 应该属于集群 DEFAULT and the group of DEFAULT_GROUP.
 */
func t5() {
	ExampleServiceClient_DeRegisterServiceInstance(client, vo.DeregisterInstanceParam{
		Ip:          "10.0.0.10",
		Port:        8848,
		ServiceName: "demo.go",
		Ephemeral:   true, //it must be true
	})
}

/**
 * 使用 ip,port,serviceName,cluster 注销 GroupName=DEFAULT_GROUP
 * Note:ip=10.0.0.10,port=8848,cluster=cluster-a 应该属于 DEFAULT_GROUP.
 */
func t6() {
	ExampleServiceClient_DeRegisterServiceInstance(client, vo.DeregisterInstanceParam{
		Ip:          "10.0.0.11",
		Port:        8848,
		ServiceName: "demo.go",
		Cluster:     "cluster-a",
		Ephemeral:   true, //it must be true
	})
}

/**
 * 取消注册 ip,port,serviceName,cluster,group
 */
func t7() {
	ExampleServiceClient_DeRegisterServiceInstance(client, vo.DeregisterInstanceParam{
		Ip:          "10.0.0.14",
		Port:        8848,
		ServiceName: "demo.go",
		Cluster:     "cluster-b",
		GroupName:   "group-b",
		Ephemeral:   true, //it must be true
	})
}

/**
 * 使用 serviceName 获取服务
 * ClusterName=DEFAULT, GroupName=DEFAULT_GROUP
 */
func t8() {
	ExampleServiceClient_GetService(client, vo.GetServiceParam{
		ServiceName: "demo.go",
	})
}

/**
 * 使用 serviceName 和 cluster 获取服务
 * GroupName=DEFAULT_GROUP
 */
func t9() {
	ExampleServiceClient_GetService(client, vo.GetServiceParam{
		ServiceName: "demo.go",
		Clusters:    []string{"cluster-a", "cluster-b"},
	})
}

/**
 * 获取服务 serviceName
 * ClusterName=DEFAULT
 */
func t10() {
	ExampleServiceClient_GetService(client, vo.GetServiceParam{
		ServiceName: "demo.go",
		GroupName:   "group-a",
	})
}

/**
 * 查询所有服务 返回所有实例 ,包括 healthy=false,enable=false,weight<=0
 * ClusterName=DEFAULT, GroupName=DEFAULT_GROUP
 */
func t11() {
	ExampleServiceClient_SelectAllInstances(client, vo.SelectAllInstancesParam{
		ServiceName: "demo.go",
	})
}

/**
 * 查询所有服务
 * GroupName=DEFAULT_GROUP
 */
func t12() {
	ExampleServiceClient_SelectAllInstances(client, vo.SelectAllInstancesParam{
		ServiceName: "demo.go",
		Clusters:    []string{"cluster-a", "cluster-b"},
	})
}

/**
 * 查询所有服务
 * ClusterName=DEFAULT
 */
func t13() {
	ExampleServiceClient_SelectAllInstances(client, vo.SelectAllInstancesParam{
		ServiceName: "demo.go",
		GroupName:   "group-a",
	})
}

/**
 * 查询说有实例 只返回的实例 healthy=${HealthyOnly},enable=true and weight>0
 * ClusterName=DEFAULT,GroupName=DEFAULT_GROUP
 */
func t14() {
	ExampleServiceClient_SelectInstances(client, vo.SelectInstancesParam{
		ServiceName: "demo.go",
	})
}

/**
 * 选择一个健康的实例 通过 WRR 策略返回一个实例进行负载均衡
 * 并且实例应该是 health=true,enable=true and weight>0
 * ClusterName=DEFAULT,GroupName=DEFAULT_GROUP
 */
func t15() {
	ExampleServiceClient_SelectOneHealthyInstance(client, vo.SelectOneHealthInstanceParam{
		ServiceName: "demo.go",
	})
}

////订阅 key=serviceName+groupName+cluster
////注意：我们使用相同的键调用添加多个 SubscribeCallback。
//param := &vo.SubscribeParam{
//	ServiceName: "demo.go",
//	Clusters:    []string{"cluster-b"},
//	SubscribeCallback: func(services []model.SubscribeService, err error) {
//		fmt.Printf("callback111 return services:%s \n\n", util.ToJsonString(services))
//	},
//}
//ExampleServiceClient_Subscribe(client, param)
//param2 := &vo.SubscribeParam{
//	ServiceName: "demo.go",
//	Clusters:    []string{"cluster-b"},
//	SubscribeCallback: func(services []model.SubscribeService, err error) {
//		fmt.Printf("callback222 return services:%s \n\n", util.ToJsonString(services))
//	},
//}
//ExampleServiceClient_Subscribe(client, param2)
//ExampleServiceClient_RegisterServiceInstance(client, vo.RegisterInstanceParam{
//	Ip:          "10.0.0.112",
//	Port:        8848,
//	ServiceName: "demo.go",
//	Weight:      10,
//	ClusterName: "cluster-b",
//	Enable:      true,
//	Healthy:     true,
//	Ephemeral:   true,
//})
////等待客户端从服务器拉取更改
//time.Sleep(10 * time.Second)
//
////现在我们只是取消订阅回调1，回调2仍然会收到更改事件
//ExampleServiceClient_UnSubscribe(client, param)
//ExampleServiceClient_DeRegisterServiceInstance(client, vo.DeregisterInstanceParam{
//	Ip:          "10.0.0.112",
//	Ephemeral:   true,
//	Port:        8848,
//	ServiceName: "demo.go",
//	Cluster:     "cluster-b",
//})
////等待客户端从服务器拉取更改
//time.Sleep(10 * time.Second)
//
////GeAllService 将获取服务名称列表
////NameSpace 默认值为public。如果客户端设置了namespaceId，NameSpace 将使用它。
////GroupName 默认值为 DEFAULT_GROUP
//ExampleServiceClient_GetAllService(client, vo.GetAllServiceInfoParam{
//	PageNo:   1,
//	PageSize: 10,
//})
//
//ExampleServiceClient_GetAllService(client, vo.GetAllServiceInfoParam{
//	NameSpace: "0e83cc81-9d8c-4bb8-a28a-ff703187543f",
//	PageNo:    1,
//	PageSize:  10,
//})
